package com.data.king.tenda.service;

/**
 * Created by lenovo on 2018/1/9.
 */
import android.content.SharedPreferences;
import android.util.Log;

import com.data.king.tenda.bean.TendaData;
import com.google.gson.Gson;
import com.mysql.jdbc.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Util {
    private static final String TAG = "Util";
    public static String TENDA_URL = "http://192.168.0.1/goform/getQos?t=";
    public static Connection openConnection(String url, String user, String password) {
        Connection conn = null;
        try {
            final String DRIVER_NAME = "com.mysql.jdbc.Driver";
            Class.forName(DRIVER_NAME);
            conn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            conn = null;
        } catch (SQLException e) {
            conn = null;
        }

        return conn;
    }

    public static void query(Connection conn, String sql) {

        if (conn == null) {
            return;
        }

        Statement statement = null;
        ResultSet result = null;

        try {
            statement = conn.createStatement();
            result = statement.executeQuery(sql);
            if (result != null && result.first()) {
                int idColumnIndex = result.findColumn("id");
                int nameColumnIndex = result.findColumn("name");
                Log.d(TAG,"id\t\t" + "name");
                while (!result.isAfterLast()) {
                    Log.d(TAG,result.getString(idColumnIndex) + "\t\t");
                    Log.d(TAG,result.getString(nameColumnIndex));
                    result.next();
                }
            }
        } catch (SQLException e) {
            Log.e(TAG,e.getMessage());
        } finally {
            try {
                if (result != null) {
                    result.close();
                    result = null;
                }
                if (statement != null) {
                    statement.close();
                    statement = null;
                }

            } catch (SQLException sqle) {

            }
        }
    }

    public static boolean execSQL(Connection conn, String sql) {
        boolean execResult = false;
        if (conn == null) {
            return execResult;
        }

        Statement statement = null;

        try {
            statement = conn.createStatement();
            if (statement != null) {
                execResult = statement.execute(sql);
            }
        } catch (SQLException e) {
            execResult = false;
        }

        return execResult;
    }

    /**
     * 将字符串转成MD5值
     *
     * @param string
     * @return
     */
    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            Log.e(TAG,e.getMessage());
            return null;
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG,e.getMessage());
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    public static void getAsynHttp() {
        OkHttpClient mOkHttpClient=new OkHttpClient();
        //Request.Builder requestBuilder = new Request.Builder().url("http://192.168.0.1/goform/getQos?t="+ (new Date().toString()));
        Request.Builder requestBuilder = new Request.Builder().url(Util.TENDA_URL+ (new Date().toString()));
        //可以省略，默认是GET请求
        requestBuilder.method("GET",null);
        Request request = requestBuilder.build();
        Call mcall= mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG,"网络请求错误" + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String resp = null;
                if(response != null && response.body() != null)
                    resp = response.body().string();
                if(StringUtils.isNullOrEmpty(resp)){
                    Log.i(TAG,"未获取响应");
                    return;
                }

                Gson gson=new Gson();
                TendaData data = gson.fromJson(resp,TendaData.class);
                if (data != null){
                    //Log.d(TAG,data.getIp());
                    DBHelper.Insert(data);
                    Log.d(TAG,"数据存储执行完毕");
                }

            }
        });
    }
}